﻿using System;
using System.Collections.Generic;
using System.Text;

namespace YouHP.Utility
{
    // 对 @1=2@3=4 的形式进行解析
    public class DataSpliter
    {
        public Dictionary<string, string> DataDictionary { get; set; }

        public DataSpliter()
        {
            DataDictionary = new Dictionary<string, string>();
        }

        public void SetDataString(string datastr)
        {
            DataDictionary.Clear();
            string[] spliter = new string[] { "@" };
            string[] spliter2 = new string[] { "=" };
            string[] datapair = datastr.Split(spliter, StringSplitOptions.RemoveEmptyEntries);
            foreach (string str in datapair)
            {
                string[] strArray = str.Split(spliter2, StringSplitOptions.RemoveEmptyEntries);
                if (strArray.Length != 2) return;
                DataDictionary.Add(strArray[0], strArray[1]);
            }
        }

        public string GetDataString()
        {
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<string, string> item in DataDictionary)
            {
                sb.AppendFormat("@{0}={1}", item.Key, item.Value);
            }
            return sb.ToString();
        }

        public string GetData(string key)
        {
            if (DataDictionary.ContainsKey(key) == false) return string.Empty;
            string data = DataDictionary[key];
            return data;
        }

        public void AddData(string key, string value)
        {
            if (DataDictionary.ContainsKey(key)) DataDictionary[key] = value;
            else DataDictionary.Add(key, value);
        }
    }
}
